package org.jeecg.modules.mall.api.taobao.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.open.api.sdk.internal.util.StringUtil;
import com.taobao.api.ApiException;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.mall.BeanMapperUtil;
import org.jeecg.common.util.mall.HttpUtils;
import org.jeecg.modules.mall.job.NewsUtils;
import org.jeecg.modules.mall.entity.Pagebean;
import org.jeecg.modules.appuser.entity.TbUserNotice;
import org.jeecg.modules.appuser.service.ITbUserNoticeService;
import org.jeecg.modules.mall.entity.*;
import org.jeecg.modules.mall.service.*;
import org.jeecg.modules.mall.service.impl.Contents;
import org.jeecg.modules.mall.util.TaoBaoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 描述
 * </p>
 */
@Slf4j
@Api(tags = "app淘宝")
@RestController
@RequestMapping("/app/taobao/api")
public class TaoBaoController {

    @Autowired
    private ITbMnMaterialOptionalService tbMnMaterialOptionalService;

    @Autowired
    private ITaobaoApiManager iTaobaoApiManager;

    @Autowired
    private ITbMnCatService tbMnCatService;
    @Autowired
    private ITbMnCatItemService tbMnCatItemService;

    @Autowired
    private IDtkManager dtkManager;

    @Autowired
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ITbUserNoticeService tbUserNoticeService;

    @Autowired
    private ITbNewChannelService tbNewChannelService;

    @Autowired
    private ITbNewsContentService tbNewsContentService;

    @Autowired
    private ITbMnAdzoneService tbMnAdzoneService;
    @Autowired
    private ITaobao_cateService taobao_cateService;

    @Autowired
    private ITb_news2Service tb_news2Service;

    //任意取一张票
    @ApiOperation("app 新闻资讯展示接口")
    @GetMapping(value = "/getNewsData")
    public Result<?> getNewsData(TbNewsContent tbNewsContent, @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                 @RequestParam(name = "pageSize", required = true) Integer pageSize, HttpServletRequest req) {
        QueryWrapper<TbNewsContent> queryWrapper = QueryGenerator.initQueryWrapper(tbNewsContent, req.getParameterMap());
        Page<TbNewsContent> page = new Page<>(pageNo, pageSize);
        queryWrapper.orderByDesc("pub_date");
        IPage<TbNewsContent> pageList = tbNewsContentService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @ApiOperation("app 新闻资讯展示接口_2")
    @GetMapping(value = "/getNewsData_2")
    public Result<?> getnew_NewsData(Tb_news2 tb_news2,Integer pageNo,Integer pageSize) {
        Page<Tb_news2> page = new Page<>(pageNo, pageSize);
        return Result.ok(tb_news2Service.getNews2DataPages(page,tb_news2));
    }



    @ApiOperation("app 新闻类目列表")
    @GetMapping(value = "/getNewsItemData")
    public Result<?> getNewsItemData() throws Exception {
        return Result.ok(tbNewChannelService.list());
    }

    @ApiOperation("淘宝热销榜top100")
    @GetMapping(value = "/getTop100")
    public Result<?> getTop100() throws Exception {

        return Result.ok(tbMnMaterialOptionalService.getTop100());
    }


    @ApiOperation("初始化淘宝状态")
    @GetMapping(value = "/initTaobaoCate")
    public Result<?> initTaobaoCate() throws Exception {

        return Result.ok(taobao_cateService.initTaobaoCate());
    }

    @AutoLog(value = "消息")
    @ApiOperation("消息")
    @PostMapping(value = "/getUserAllNotice")
    public Result<?> getUserNotice(TbUserNotice tbUserNotice,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Page<TbUserNotice> page = new Page<TbUserNotice>(pageNo, pageSize);
        IPage<TbUserNotice> pageList = tbUserNoticeService.page(page, tbUserNotice);
        return Result.ok(pageList);

    }


    @AutoLog(value = "获取首页商品列表和9.9包邮")
    @ApiOperation(value = "获取首页商品列表和9.9包邮", notes = "9.9 type参数传99")
    @GetMapping(value = "/app/index/getProductList")
    public Result<?> getPageList(TbMnMaterialOptional tbMnMaterialOptional, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        log.info("开始获取商品元素,dat:{}", DateUtil.currentSeconds());

        QueryWrapper<TbMnMaterialOptional> queryWrapper = QueryGenerator.initQueryWrapper(tbMnMaterialOptional, req.getParameterMap());
        Page<TbMnMaterialOptional> page = new Page<TbMnMaterialOptional>(pageNo, pageSize);
        IPage<TbMnMaterialOptional> pageList = null;
        if (null != tbMnMaterialOptional.getType() && tbMnMaterialOptional.getType().equals("99")) {
            if (StringUtil.isEmpty(tbMnMaterialOptional.getSort())) {
                tbMnMaterialOptional.setSort("zk_final_price");
            }
            pageList = tbMnMaterialOptionalService.pageChoiceness(page, tbMnMaterialOptional);
        } else {
            pageList = tbMnMaterialOptionalService.page(page, queryWrapper);

        }

        log.info("结束获取商品元素,dat:{}", DateUtil.currentSeconds());

        return Result.ok(pageList);
    }


    /**
     * 获取首页商品列表
     */
    @AutoLog(value = "获取首页商品列表指定")
    @ApiOperation(value = "获取指定商品列表", notes = "指定")
    @GetMapping(value = "/app/index/getCentreList")
    public Result<?> getCentreList(TbMnMaterialOptional tbMnMaterialOptional, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        log.info("开始获取商品元素,dat:{}", DateUtil.currentSeconds());

        QueryWrapper<TbMnMaterialOptional> queryWrapper = QueryGenerator.initQueryWrapper(tbMnMaterialOptional, req.getParameterMap());
        Page<TbMnMaterialOptional> page = new Page<>(pageNo, pageSize);
        IPage<TbMnMaterialOptional> pageList = tbMnMaterialOptionalService.getMaterialOptionalList(page, tbMnMaterialOptional);

        log.info("结束获取商品元素,dat:{}", DateUtil.currentSeconds());
        return Result.ok(pageList);
    }

    @AutoLog(value = "获取首页商品列表 随机获取")
    @ApiOperation(value = "获取首页商品列表", notes = "随机获取")
    @GetMapping(value = "/app/index/getCentreListRandom")
    public Result<?> getCentreListRandom(TbMnMaterialOptional tbMnMaterialOptional, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        log.info("开始获取商品元素,dat:{}", DateUtil.currentSeconds());

        QueryWrapper<TbMnMaterialOptional> queryWrapper = QueryGenerator.initQueryWrapper(tbMnMaterialOptional, req.getParameterMap());
        Page<TbMnMaterialOptional> page = new Page<>(pageNo, pageSize);
        IPage<TbMnMaterialOptional> pageList = tbMnMaterialOptionalService.getCentreList(page, tbMnMaterialOptional);
        log.info("结束获取商品元素,dat:{}", DateUtil.currentSeconds());
        return Result.ok(pageList);
    }


    @AutoLog(value = "删除0元返佣商品")
    @ApiOperation(value = "删除0元返佣商品")
    @GetMapping(value = "/deleteTbMnMaterialOptional")
    public Result<?> deleteTbMnMaterialOptional(String num_iid) {
        log.info("开始获取商品元素,dat:{}", DateUtil.currentSeconds());

        return tbMnMaterialOptionalService.deleteTbMnMaterialOptional(num_iid);
    }

    @AutoLog(value = "得到新的分享token")
    @ApiOperation(value = "得到新的分享token")
    @GetMapping(value = "/getNewShareToken")
    public Result<?> getNewShareToken(String num_iid, String user_id) {
        log.info("开始获取商品元素,dat:{}", DateUtil.currentSeconds());
        return tbMnMaterialOptionalService.getNewShareToken(num_iid, user_id);
    }


    @AutoLog(value = "获取类目元素")
    @ApiOperation(value = "获取类目元素", notes = "获取类目元素")
    @GetMapping(value = "/app/classify/getCats")
    public Result<?> getCats() {
        log.info("获取类目元素列表");
        QueryWrapper<TbMnCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        return Result.ok(tbMnCatService.list(queryWrapper));
    }


    @AutoLog(value = "获取类目元素列表")
    @ApiOperation(value = "获取类目元素列表", notes = "获取类目元素列表")
    @GetMapping(value = "/app/classify/getCatList")
    public Result<?> getCatList(TbMnCatItem tbMnCatItem, HttpServletRequest req) {
        log.info("获取类目元素列表");
        QueryWrapper<TbMnCatItem> queryWrapper = QueryGenerator.initQueryWrapper(tbMnCatItem, req.getParameterMap());
        queryWrapper.orderByDesc("sort");
        return Result.ok(tbMnCatItemService.list(queryWrapper));
    }


    @AutoLog(value = "获取二级类目列表")
    @ApiOperation(value = "获取二级类目列表", notes = "获取二级类目列表")
    @PostMapping(value = "/app/classify/skipProduct")
    public Result<?> skipProduct(TbMnCatItem tbMnCatItem) {
        log.info("跳转到指定的产品列表,tbMnCatItem{}", tbMnCatItem);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cat_id", tbMnCatItem.getCatId());
        queryWrapper.orderByAsc("sort");
        List<TbMnCatItem> tbMnCatItemList = tbMnCatItemService.list(queryWrapper);
        Map<String, Object> resultMap = new HashMap<>();
        //获取一级类目名称
        TbMnCat catDo = tbMnCatService.getOne(queryWrapper);
        resultMap.put("tbMnCatItemList", tbMnCatItemList);
        resultMap.put("catName", catDo.getCatName());
        resultMap.put("catId", tbMnCatItem.getCatId());
        return Result.ok(resultMap);
    }

    @GetMapping(value = "/app/classify/skipProductList")
    public Result<?> skipProductList(TbMnMaterialOptional tbMnMaterialOptional) {
        //获取类目名称
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("category_name", tbMnMaterialOptional.getCategoryName());
        TbMnCatItem tbMnCatItem = tbMnCatItemService.getOne(queryWrapper);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("itemCat", tbMnCatItem);
        return Result.ok(resultMap);

    }


    @AutoLog(value = "转链")
    @ApiOperation(value = "转链", notes = "转链")
    @PostMapping(value = "/app/query/zhuanlian")
    public Result<?> zhanlian(String zhuanlian, HttpServletResponse response) {
        String numIid = "1";
        String url = null;
        log.info("转链请求,zhuanlian:{}", zhuanlian);
        try {
            if (zhuanlian.contains("€")) {
                Pattern pattern1 = Pattern.compile("€(\\w+)€");
                Matcher matcher1 = pattern1.matcher(zhuanlian);
                if (matcher1.find()) {
                    url = "https://api.open.21ds.cn/apiv1/tpwdtoid?apkey=105bc582-a6b2-9c26-4e9d-e5bb9657c2c8&tpwd=€" + matcher1.group(1) + "€";
                }
            }

            if (zhuanlian.contains("￥")) {
                Pattern pattern2 = Pattern.compile("￥(\\w+)￥");
                Matcher matcher2 = pattern2.matcher(zhuanlian);
                if (matcher2.find()) {
                    url = "https://api.open.21ds.cn/apiv1/tpwdtoid?apkey=105bc582-a6b2-9c26-4e9d-e5bb9657c2c8&tpwd=￥" + matcher2.group(1) + "￥";
                }
            }
            log.info(url);
            String rsp = HttpUtils.httpClientGet(url, "");
            log.info(rsp);
            JSONObject jsonObject = JSONObject.parseObject(rsp);
            log.info(jsonObject.getString("code"));
            if ("200".equals(jsonObject.getString("code"))) {
                log.info("转链成功");
                return Result.ok(jsonObject.getString("data"));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.ok(numIid);
    }

    /**
     * 超级搜索产品列表
     */
    @AutoLog(value = "超级搜索产品列表")
    @ApiOperation(value = "超级搜索产品列表", notes = "超级搜索产品列表")
    @PostMapping(value = "/app/query/superQueryList")
    public Result<?> superQueryList(TbkDgMaterialOptionalRequest request) {
        log.info("跳转到产品列表,optionalDo:{}", request.toString());

        log.info("跳转到产品列表,optionalDo:{}", request.toString());
        List<TbkDgMaterialOptionalResponse.MapData> mapData = null;
        try {
            mapData = iTaobaoApiManager.getSuperQueryList(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return Result.ok(mapData);
    }

    @AutoLog(value = "打开淘宝页面")
    @ApiOperation(value = "打开淘宝页面", notes = "打开淘宝页面")
    @GetMapping(value = "/app/detail/openskipProductDetail")
    public Result<?> openskipProductDetail(String numIid, String user_id) throws ApiException {
        String itemUrl = "https://detail.tmall.com/item.htm?id=" + numIid;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", user_id);
        TbMnAdzone tbMnAdzone = tbMnAdzoneService.getOne(queryWrapper);
        if (null != tbMnAdzone) {
            String adzoneId = tbMnAdzone.getAdzoneId();
            adzoneId = adzoneId.trim();
            if (adzoneId.indexOf("l") > -1) {
                adzoneId = adzoneId.substring(0, adzoneId.length() - 1);
            }
            Long adzoned = Long.valueOf(adzoneId);
            TbkDgMaterialOptionalResponse.MapData mapData = iTaobaoApiManager.getProductByItemUrl(itemUrl, adzoned);
            if (null == mapData) {
                return Result.ok("adzone_id不存在");
            }
            System.out.println(mapData.toString() + "----\n\n");
            TbMnMaterialOptional optionalDo1 = BeanMapperUtil.objConvert(mapData, TbMnMaterialOptional.class);

            return Result.ok(optionalDo1);
        }

        return Result.ok("错误");

    }


    @AutoLog(value = "获取商品详情")
    @ApiOperation(value = "获取商品详情", notes = "获取商品详情")
    @GetMapping(value = "/app/detail/skipProductDetail")
    public Result<?> skipProductDetail(TbMnMaterialOptional optionalDo, String type, String user_id) {

        Map<String, Object> resultMap = new HashMap<>();
        try {
            log.info("开始跳转到商品详情,numIid:{},date:{}", optionalDo.getNumIid(), DateUtil.currentSeconds());

            // TODO  判断用户是否登陆，登陆后才能获取到返利，否则算是自己的
            Long adzoneId = Contents.adzone_id;
            String tbkRate = "60";
            boolean flag = false;
            if (user_id != null) {
                String account = "";
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("account", user_id);
                TbMnUser tbMnUser = tbMnUserService.getOne(queryWrapper);
                if (null != tbMnUser) {
                    flag = true;
                    log.info("查询订单详情,adzoneId:{},accountNo:{}", adzoneId, account);
                    tbkRate = tbMnUser.getOwnRate();
                }
            }
            TbMnProductDetail itemDetail = null;
            TbMnMaterialOptional optionalDo1 = null;
            String itemUrl = "https://detail.tmall.com/item.htm?id=" + optionalDo.getNumIid();
            //通过物料搜索接口获取优惠券信息
            String couponAmonunt = null;
            String smallImages = null;
            String command = null;
            try {
                log.info("查询订单详情,adzoneId:{}", adzoneId);
                TbkDgMaterialOptionalResponse.MapData mapData = iTaobaoApiManager.getProductByItemUrl(itemUrl, adzoneId);
                System.out.println(mapData.toString() + "----\n\n");
                optionalDo1 = BeanMapperUtil.objConvert(mapData, TbMnMaterialOptional.class);

                if (null == mapData.getSmallImages()) {
                    smallImages = mapData.getPictUrl();
                } else {
                    smallImages = getSmallImages(mapData.getSmallImages());
                }
                if (null != optionalDo1.getCouponEndTime()) {
                    couponAmonunt = dtkManager.getCouponAmount(mapData);
                    optionalDo1.setCouponShareUrl(optionalDo1.getCouponShareUrl());
                } else {
                    couponAmonunt = "0";
                    optionalDo1.setCouponShareUrl(optionalDo1.getUrl());
                }
                command = dtkManager.getCommand(mapData);
                optionalDo1.setCouponAmount(couponAmonunt);
                optionalDo1.setSmallImages(smallImages);
                optionalDo1.setToken(command);
                resultMap.put("rate", (new BigDecimal(optionalDo1.getZkFinalPrice()).subtract(new BigDecimal(couponAmonunt))).multiply(new BigDecimal(optionalDo1.getCommissionRate())).multiply(new BigDecimal(tbkRate)).divide(new BigDecimal(Double.toString(1000000))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                //获取商品详情
                TbkItemInfoGetResponse.NTbkItem item = iTaobaoApiManager.queryProductItem(String.valueOf(mapData.getNumIid()));
                itemDetail = BeanMapperUtil.objConvert(item, TbMnProductDetail.class);

                //如果商品存在本地库，则查询出推荐语
                optionalDo1 = tbMnMaterialOptionalService.queryRecommendMsg(optionalDo1);
            } catch (ApiException e) {
                e.printStackTrace();
            }
            String afterAmount = getAfterAmount(optionalDo1);
            resultMap.put("optionalDo", optionalDo1);
            resultMap.put("images", optionalDo1.getSmallImages().split(","));
            resultMap.put("itemDetail", itemDetail);
            resultMap.put("afterAmount", afterAmount);
            resultMap.put("flag", flag);

            log.info("结束跳转到商品详情,numIid:{},date:{}", optionalDo.getNumIid(), DateUtil.currentSeconds());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.ok(resultMap);
    }


    private String getAfterAmount(TbMnMaterialOptional tbMnMaterialOptional) {

        if (null != tbMnMaterialOptional) {
            String zkfinalPrice = "0";

            if (null == tbMnMaterialOptional.getZkFinalPrice()) {
                zkfinalPrice = tbMnMaterialOptional.getZkFinalPrice();
            }
            BigDecimal bigA = new BigDecimal(zkfinalPrice);
            BigDecimal bigB = new BigDecimal(tbMnMaterialOptional.getCouponAmount());
            return String.valueOf(bigA.subtract(bigB).doubleValue());
        }
        return "0";
    }


    private String getSmallImages(List<String> list) {
        StringBuffer sb = new StringBuffer();
        for (String str : list) {
            sb.append(str);
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
